/**
 * 项目名称:
 *
 * @Author: 夏国倩
 * @Date: 2023/10/16 14:02
 * @Copyright
 */
package JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCtest5 {
    public static void main(String[] args) {
        Connection conn=null;
        Statement stmt=null;
        ResultSet rs=null;
        try{
          //1. 注册驱动
          Class.forName("com.mysql.cj.jdbc.Driver");
          //2.获取连接
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/base1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC",
                    "root",
                    "123456");
            //3.获取数据库操作对象
            stmt=conn.createStatement();
            //4.执行SQL
            String sql="select id,username from user";
            //int executeUpdate(insert/delete/update);
            //ResultSet executeQuery(select)
            rs=stmt.executeQuery(sql); //专门执行DQL语句的方法
            //5.处理查询结果集
            /*boolean flag1=rs.next();
            System.out.println(flag1);
            if (flag1){
                //光标指向行有数据
                //取数据
                //getString()方法的特点是：不管数据库中的数据类型是什么，都是以String的形式取出
                String id = rs.getString(1); //JDBC中所有下标从1开始
                String username = rs.getString(2);
                System.out.println(id+","+username);
            }
            flag1 = rs.next();
            if (flag1){
                String id=rs.getString(1);
                String username = rs.getString(2);
                System.out.println(id+","+username);*/
            while (rs.next()){
                //是以列的下标获取
                //String id=rs.getString(1);
               // String username=rs.getString(2);
                //以列的名字获取
                //String id=rs.getString("id");
                //String username=rs.getString("username");
                //String username=rs.getString("name"); //重点注意：列名称不是表中的列名称

                //除了可以以String类型取出，还可以以特定的类型取出
                int id = rs.getInt(1);
                String username = rs.getString(2);
                System.out.println(id+","+username);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //6.释放资源
            if (rs != null){
                try{
                    rs.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (conn != null){
                try{
                    conn.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
